package de.gist.calldurationwatcher.services;

import de.gist.calldurationwatcher.activities.R;
import de.gist.calldurationwatcher.helper.CallLogFields;
import de.gist.calldurationwatcher.helper.CallLogHelper;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Binder;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;

public class CallLoggingService extends Service {

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	public class CallLogServiceBinder extends Binder {
		public CallLoggingService getService() {
			return CallLoggingService.this;
		}
	}
	
	public void UpdateFreeMinutesLeft(Context context) {
		
		Cursor cursor = CallLogHelper.getCallCursor(context);
		
		if (cursor == null)
			return;
		
		try {
		
			if (cursor.moveToFirst()) {
				int duration = Integer.getInteger(cursor.getString(CallLogFields.DURATION.ordinal()));
				SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
				int minutesLeft = prefs.getInt(getString(R.string.minutesLeft), -1);
				if (minutesLeft == -1)
					return;
				SharedPreferences.Editor editor = prefs.edit();
				editor.putInt(getString(R.string.minutesLeft), minutesLeft - duration);
				editor.commit();
			}
		} catch (Exception ex) {
			Log.e("CallLoggingService", ex.getMessage());
		}
	}
}
